package com.lpfy.dtxc;

import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.lpfy.dtxc.bean.FileResBean;
import com.lpfy.dtxc.download.AbsFileProgressCallback;
import com.lpfy.dtxc.download.DownloadFileUtils;
import com.lpfy.dtxc.playerView.FilePlayerView;
import com.lpfy.dtxc.receiver.NetworkConnectChangedReceiver;
import com.lpfy.dtxc.utils.DeviceUtil;
import com.lpfy.dtxc.utils.KVUtils;
import com.lpfy.dtxc.utils.MNUtils;
import com.tencent.dtxc.R;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author: hanGuangHui
 * @data: 2024/2/27
 * @description:
 */
public class HomeActivity extends AppCompatActivity {

    private List<BVImageBean> fileBean = new ArrayList<>();

    private FilePlayerView filePlayerView;
    private LinearLayout llLoading;

    /**
     * 文件下载的保存路劲
     */
    private String filePath;

    private String mVersion;

    private int playDelay = 10 * 60 * 1000;

    private boolean downloading = false;

    /**
     * 判断是否是首次打开
     */
    private boolean firstOpen = true;

    private String saveFileFolderPath;

    private Timer timer = new Timer();
    private TimerTask timerTask;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        saveFileFolderPath = MNUtils.getCachePath(HomeActivity.this) + "/dtxcFile/";
        initImmersionBar();
        llLoading = findViewById(R.id.ll_loading);
        filePlayerView = findViewById(R.id.file_play);
        initTime();
        requestFile();
//        createTestData();
    }

    private void createTestData() {
        llLoading.setVisibility(View.GONE);
        FileResBean fileResBean = new FileResBean();
        fileResBean.setVersion("3");
        ArrayList<FileResBean.ItemBean> itemBeans = new ArrayList<>();
        itemBeans.add(new FileResBean.ItemBean("image", 5, "https://t11.baidu.com/it/app=106&f=JPEG&fm=30&fmt=auto&u=3466545771%2C228890699?w=312&h=208&s=AD26C3141E504E5FD6B62ECE0300B0AF"));
        itemBeans.add(new FileResBean.ItemBean("web", 5, "https://baijiahao.baidu.com/s?id=1792397009358547036"));
        itemBeans.add(new FileResBean.ItemBean("image", 5, "https://t11.baidu.com/it/app=106&f=JPEG&fm=30&fmt=auto&u=3466545771%2C228890699?w=312&h=208&s=AD26C3141E504E5FD6B62ECE0300B0AF"));
        itemBeans.add(new FileResBean.ItemBean("web", 5, "https://www.youdao.com/result?word=%E6%84%8F%E8%A7%81&lang=en"));
        itemBeans.add(new FileResBean.ItemBean("web", 5, "http://200.nxmcs.com:9000/shareScreen/eyJzY3JlZW5JZCI6MTE2OTN9"));

        fileResBean.setItem(itemBeans);

        mVersion = fileResBean.getVersion();
        String version1 = KVUtils.get().getString("version");
        if (fileResBean.getVersion().equals(version1)) {
            if (!firstOpen) {
                return;
            }
            firstOpen = false;
            readLocalData();
            filePlayerView.setData(fileBean);
            return;
        }
        firstOpen = false;
        runOnUiThread(() -> dealFile(fileResBean));
    }

    /**
     * 请求资源
     */
    private void requestFile() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60000, TimeUnit.MILLISECONDS).build();
        Request request = new Request.Builder()
                .get()
                .url("http://jn.nxpi.org:9000/release/content.jspx?devid=" +  DeviceUtil.getSerial(this))
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    llLoading.setVisibility(View.GONE);
                    readLocalData();
                });
                Log.e("资源拉取结果", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) {
                runOnUiThread(() -> {
                    llLoading.setVisibility(View.GONE);
                    try {
                        if (response.body() == null) {
                            //如果本地有缓存，读取本地缓存，非首次打开
                            if (!firstOpen) {
                                return;
                            }
                            readLocalData();
                            return;
                        }
                        String finalStr = response.body().string();
                        Log.e("资源拉取结果", finalStr);
                        if(finalStr.isEmpty()){
                            //如果本地有缓存，读取本地缓存，非首次打开
                            if (!firstOpen) {
                                return;
                            }
                            readLocalData();
                            return;
                        }
                        FileResBean bean = new Gson().fromJson(finalStr, FileResBean.class);
                        mVersion = bean.getVersion();
                        String version1 = KVUtils.get().getString("version");
                        if (bean.getVersion().equals(version1)) {
                            if (!firstOpen) {
                                return;
                            }
                            readLocalData();
                            return;
                        }
                        deleteLocalData();
                        dealFile(bean);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }

    /**
     * 将资源封装，pdf资源需要下载后转换成图片
     */
    private void dealFile(FileResBean bean) {
        fileBean.clear();
        for (int i = 0; i < bean.getItem().size(); i++) {
            FileResBean.ItemBean bean1 = bean.getItem().get(i);
            fileBean.add(new BVImageBean(bean1.getUrl(), bean1.getType(), bean1.getDuration() * 1000));
        }
        boolean isAllWeb = true;
        for (int i = 0; i < fileBean.size(); i++) {
            if (!fileBean.get(i).getFileType().equals("web")) {
                isAllWeb = false;
                startDownloadFile(i, fileBean.get(i).getFilePath(),fileBean.get(i).getFileType());
                break;
            }
        }
        //证明全是网页，不用下载
        if (isAllWeb) {
            filePlayerView.setData(fileBean);
            saveToLocal();
            llLoading.setVisibility(View.GONE);
            firstOpen = false;
        }
    }

    /**
     * 删除本地资源
     */
    public void deleteLocalData() {
        deleteFolderRecursively(new File(saveFileFolderPath));
        KVUtils.get().putString("bean", "");
        KVUtils.get().putString("version", "");
    }

    /**
     * 保存到本地
     */
    private void saveToLocal() {
        KVUtils.get().putString("bean", new Gson().toJson(fileBean));
        KVUtils.get().putString("version", mVersion);
    }

    /**
     * 读取本地资源
     */
    private void readLocalData() {
        String json = KVUtils.get().getString("bean");
        Gson gson = new Gson(); // 创建 Gson 对象
        Type listType = new TypeToken<ArrayList<BVImageBean>>() {
        }.getType(); // 定义要转换的类型
        fileBean = gson.fromJson(json, listType);
        if (fileBean!=null && fileBean.size() > 0) {
            filePlayerView.setData(fileBean);
            firstOpen = false;
        }
    }

    /**
     * 开始下载文件
     */
    private void startDownloadFile(int index, String fileUrl,String type) { //判断下载保存路径是不是空
        if (downloading) {
            return;
        }
        downloading = true;
        if (firstOpen) {
            llLoading.setVisibility(View.VISIBLE);
        }
        String[] split = fileUrl.split("\\.");
        String end = "";
        if (split.length > 1) {
            end = split[split.length - 1];
        }
        if ("video".equals(type)){
            end="mp4";
        }
        filePath = saveFileFolderPath + System.currentTimeMillis() + "." + end;
        Log.e("-----------存储目录", filePath);
        MNUtils.changeApkFileMode(new File(filePath));
        DownloadFileUtils.with()
                .downloadPath(filePath)
                .url(fileUrl)
                .tag(HomeActivity.class)
                .execute(new AbsFileProgressCallback() {
                    @Override
                    public void onSuccess(String result) {
                        boolean flag = true;
                        downloading = false;
                        Log.e("下载进度", "下载成功" + filePath);
                        fileBean.get(index).setFileUrl(filePath);
                        //循环下载资源
                        for (int i = 0; i < fileBean.size(); i++) {
                            if (!fileBean.get(i).getFileType().equals("web")
                                    && fileBean.get(i).getFilePath().contains("http")) {
                                flag = false;
                                startDownloadFile(i, fileBean.get(i).getFilePath(),fileBean.get(i).getFileType());
                                break;
                            }
                        }
                        //所有资源下载完毕
                        if (flag) {
                            filePlayerView.setData(fileBean);
                            saveToLocal();
                            llLoading.setVisibility(View.GONE);
                            firstOpen = false;
                        }
                    }

                    @Override
                    public void onProgress(long bytesRead, long contentLength, boolean done) {
                        if (contentLength > 0) {
                            //计算进度
                            int progress = (int) (bytesRead * 100 / contentLength);
                            Log.e("下载进度", progress + "");
                        }
                    }

                    @Override
                    public void onFailed(String errorMsg) {
                        Log.e("下载进度", "下载失败");
                    }

                    @Override
                    public void onStart() {
                        Log.e("下载进度", "下载开始");
                    }

                    @Override
                    public void onCancel() {
                        Log.e("下载进度", "取消下载");
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (filePlayerView != null) {
            filePlayerView.onDestroy();
        }
        cancelTime();
    }

    protected void initImmersionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setNavigationBarColor(getResources().getColor(R.color.pureWhite));
        }
        //设置共同沉浸式样式
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .init();
    }

    /**
     * 删除本地缓存的文件
     */
    public void deleteFolderRecursively(File folder) {
        try {
            if (folder.exists() && folder.isDirectory()) {
                File[] files = folder.listFiles();
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteFolderRecursively(file);
                    } else {
                        if(!file.getAbsolutePath().endsWith("mp4")){
                          file.delete();
                        }

                    }
                }
                folder.delete();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private void initTime(){
        timerTask = new TimerTask() {
            @Override
            public void run() {
                requestFile();
            }
        };
        timer.schedule(timerTask, 0, playDelay);
    }

    private void cancelTime(){
        if(timer!= null){
            timer.cancel();
            timer = null;
        }
        if(timerTask!=null){
            timerTask.cancel();
            timerTask = null;
        }
    }
}
